package awk.script.javassist.field02;
//import javassist.*;

import cn.hutool.core.io.FileUtil;
import javassist.*;

import java.io.IOException;

/**
 * @author yujianlong
 * @create 2021-03-19 23:47
 **/
public class AddField {
	public static void main(String[] args) throws NotFoundException, CannotCompileException, IOException {


		ClassPool classPool = ClassPool.getDefault();

		classPool.importPackage("java.util.List");
		classPool.importPackage("java.util.ArrayList");

		//创建类 用makeClass
		CtClass ctClass = classPool.makeClass("com.yu.test.javassist.create01.testClass04");

		//添加属性
		ctClass.addField(CtField.make("private int para = 5;", ctClass));

		//添加setPara方法
		ctClass.addMethod(CtMethod.make("public void setPara(int para){this.para = para;}", ctClass));
		ctClass.addMethod(CtMethod.make("public int getPara(){return this.para;}", ctClass));

		//另一种添加属性的办法
		CtField field = new CtField(classPool.get(String.class.getName()), "value", ctClass);
		field.setModifiers(Modifier.PRIVATE);
		// 添加getter和setter方法
		ctClass.addMethod(CtNewMethod.setter("setValue", field));
		ctClass.addMethod(CtNewMethod.getter("getValue", field));
		ctClass.addField(field);


//		ctClass.addField(CtField.make("private java.util.List/*<String>*/ containers = new java.util.ArrayList/*<>*/();", ctClass));
//
//		ctClass.addMethod(CtMethod.make("public java.util.List/*<String>*/ getContainers() {\n" +
//				"\t\treturn containers;\n" +
//				"\t}", ctClass));
//		ctClass.addMethod(CtMethod.make("public void setContainers(java.util.List/*<String>*/ containers) {\n" +
//				"\t\tthis.containers = containers;\n" +
//				"\t}", ctClass));

		ctClass.addField(CtField.make("private List/*<String>*/ containers = new ArrayList/*<>*/();", ctClass));

		ctClass.addMethod(CtMethod.make("public List/*<String>*/ getContainers() {\n" +
				"\t\treturn containers;\n" +
				"\t}", ctClass));
		ctClass.addMethod(CtMethod.make("public void setContainers(List/*<String>*/ containers) {\n" +
				"\t\tthis.containers = containers;\n" +
				"\t}", ctClass));

		//添加main方法
		CtMethod mainMethod =CtMethod.make(
				"public static void main(String[] args) {\n" +
						"\t\tSystem.out.println(\"hello,xdf,this my test04\");\n" +
						"\t\tSystem.out.println(\"你好世界\");\n" +
						"\t}",
				ctClass
		);

		//新类添加上方法
		ctClass.addMethod(mainMethod);


		//或者生成到指定目录
		//将ctClass生成字节数组，并写入文件
		byte[] byteArray = ctClass.toBytecode();
		String writeFilePath = "/Users/yujianlong/Movies/test3/testClass04.class";

		FileUtil.writeBytes(byteArray,writeFilePath);

	}

}
